<?php
namespace app\store\model\user;

use app\common\model\user\Sn as SnModel;

/**
 * 设备sn模型
 * Class Sn
 * @package app\store\model\user
 */
class Sn extends SnModel
{
    /**
     * 获取设备Sn列表
     * @param string $search
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getList($search = '')
    {
        // 构建查询规则
        $this->alias('sn')
            ->field('sn.*, user.avatarUrl, user.mobile')
            ->join('user', 'user.user_id = sn.user_id')
            ->where('sn.is_delete', '=', 0)
            ->order(['sn.create_time' => 'desc']);
        // 查询条件
        !empty($search) && $this->where('user.mobile|sn.real_name|sn.device_sn', 'like', "%$search%");
        // 获取列表数据
        return $this->paginate(15, false, [
            'query' => \request()->request()
        ]);
    }

    /**
     * 添加设备SN码
     * @param $data
     * @return bool
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function addSn($data)
    {
        if (!$this->validation($data)) {
            return false;
        }
        $data['wxapp_id'] = self::$wxapp_id;
        return $this->allowField(true)->save($data);
    }

    /**
     * 验证数据
     * @param $data
     * @param $type 类型
     * @return bool
     */
    private function validation($data, $type = 10)
    {
        if ($type == 10) {
            if(!isset($data['user_id']) || !$data['user_id']) {
                $this->error = '请选择用户后提交';
                return false;
            }
        }
        if (!isset($data['real_name']) || empty($data['real_name'])) {
            $this->error = "请填写姓名";
            return false;
        }
        if (!isset($data['gender']) || empty($data['gender'])) {
            $this->error = "请选择性别";
            return false;
        }
        if (!isset($data['device_sn']) || empty($data['device_sn'])) {
            $this->error = "请填写设备SN码";
            return false;
        }
        return true;
    }

    /**
     * 更新记录
     * @param $data
     * @return bool|int
     */
    public function edit($data)
    {
        if (!$this->validation($data, 20)) {
            return false;
        }
        return $this->allowField(true)->save($data) !== false;
    }

    /**
     * 软删除
     * @return false|int
     */
    public function setDelete()
    {
        return $this->save(['is_delete' => 1]);
    }

}